package red;

import java.awt.Dimension;

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;

import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import enlace.FachadaCapaEnlaceParaCapaDeRed;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Cursor;
import java.awt.ComponentOrientation;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

public class Main extends JFrame{
	
	boolean primeraVezLlenandoElInbox = true;
	
	public Main() {
		
		JPanel panel = new JPanel();
		panel.setAlignmentX(Component.LEFT_ALIGNMENT);
		panel.setAlignmentY(Component.TOP_ALIGNMENT);
		getContentPane().add(panel, BorderLayout.CENTER);
		
		outbox = new JTextField();
		outbox.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
		outbox.setColumns(10);
		outbox.setDocument(new JTextFieldLimit(1024));
				
		JButton btnSend = new JButton("Send");
		btnSend.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				String message = outbox.getText();
				do {
					message += " ";
				} while (message.length() < 1024);
				outbox.setText("");
                System.out.println("[Capa de Red] Enviando paquete: \"" + message + "\"");
                try {
                        FachadaCapaEnlaceParaCapaDeRed.getInstancia().enviarPaquete(message);
                } catch (Exception e) {
                        e.printStackTrace();
                }
			}
		});
		btnSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING, false)
						.addComponent(scrollPane, Alignment.LEADING)
						.addComponent(outbox, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnSend, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(40, Short.MAX_VALUE))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(outbox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnSend, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		
		inbox = new JTextArea();
		scrollPane.setViewportView(inbox);
		inbox.setFocusable(false);
		inbox.setLineWrap(true);
		inbox.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
		inbox.setAlignmentY(Component.TOP_ALIGNMENT);
		inbox.setAlignmentX(Component.LEFT_ALIGNMENT);
		inbox.setColumns(10);
		panel.setLayout(gl_panel);
	}
	static Main main;
	private JTextField outbox;
	private JTextArea inbox;
	public static void main( String[] args ){ 
		System.out.println("[Capa De Red] Capa de red levantada");
		main = new Main();
		main.init();
		FachadaCapaEnlaceParaCapaDeRed.getInstancia().suscribirse(main);
		try {
			FachadaCapaEnlaceParaCapaDeRed.getInstancia().recibirPaquete();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void init() {

		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {

				setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

				setSize(new Dimension(450, 300));

				setVisible(true);
			}
		});

	}

	public void response(String resp) {
		String contenidoEstilado = eliminarEspaciosEnBlanco(resp);
		if (primeraVezLlenandoElInbox){
			inbox.setText(inbox.getText() + contenidoEstilado);
			primeraVezLlenandoElInbox = false;
		} else {
			inbox.setText(inbox.getText() + "\n" + contenidoEstilado);
		}
		reproducirSonido("send.mp3");
		System.out.println("[Capa De Red] Nuevo paquete recibido");
	}
	
	private String eliminarEspaciosEnBlanco(String resp) {
		int ultimoCaracter = 1024;
		while(resp.charAt(ultimoCaracter-1) == ' '){
			ultimoCaracter--;
		}
		return resp.substring(0, ultimoCaracter);
		
	}

	private void reproducirSonido(String path){
	    try {
	        FileInputStream fis;
	        Player player;
	        fis = new FileInputStream(path);
	        BufferedInputStream bis = new BufferedInputStream(fis);

	        player = new Player(bis);
	        player.play();         
	    } catch (JavaLayerException e) {
	    	System.out.println("No layer");
	        e.printStackTrace();
	    } catch (FileNotFoundException e) {
	    	System.out.println("No file");
	        e.printStackTrace();
	    }
	}
}
